using System;
using System.Threading.Tasks;
using JTTD.Common.Helper;
using JTTD.Domain.Dtos;
using JTTD.Domain.Dtos.WeiXin;
using JTTD.Domain.IService;
using JTTD.Domain.Units;
using Newtonsoft.Json;

namespace JTTD.Domain.Service
{
    public class WeiXinService : IWeiXinService
    {
        private string appId;

        private string appSecret;

        public WeiXinService()
        {
            appId = ConfigHelper.GetConfigValue("WeChat:appId");
            appSecret = ConfigHelper.GetConfigValue("WeChat:appsecret");
        }

        /// <summary>
        /// 获取accessToken
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task<ApiResult<OAuthToken>> GetAccessToken(string code)
        {
            try
            {
                string url =
                    $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={appId}&secret={appSecret}&code={code}&grant_type=authorization_code";
                Console.WriteLine(url);
                string resultStr = HttpHelper.GetStringAsync(url);
                Console.WriteLine(resultStr);
                var token = JsonConvert.DeserializeObject<OAuthToken>(resultStr);
                return !string.IsNullOrEmpty(token.access_token)
                    ? ApiResultUnit.Success(token)
                    : ApiResultUnit.Error<OAuthToken>(resultStr);
            }
            catch (Exception ex)
            {
                StringHelper.AddLgoToTXT(ex.ToString());
                return ApiResultUnit.Error<OAuthToken>(ex.ToString());
            }
        }


        /// <summary>
        /// 获取微信用户信息
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<WXOAuthUserInfo>> GetWXOAuthUserInfo(string accessToken, string openId)
        {
            try
            {
                string url =
                    $"https://api.weixin.qq.com/sns/userinfo?access_token={accessToken}&openid={openId}&lang=zh_CN";
                Console.WriteLine(url);
                string resultStr = HttpHelper.GetStringAsync(url);
                Console.WriteLine(resultStr);
                var user = JsonConvert.DeserializeObject<WXOAuthUserInfo>(resultStr);
                return !string.IsNullOrEmpty(user.openid)
                    ? ApiResultUnit.Success(user)
                    : ApiResultUnit.Error<WXOAuthUserInfo>(resultStr);
            }
            catch (Exception ex)
            {

                StringHelper.AddLgoToTXT(ex.ToString());
                return ApiResultUnit.Error<WXOAuthUserInfo>(ex.ToString());
            }
        }
    }
}